<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="btn">点击</button>
    <script>
      // 防抖 ：n 秒后在执行该事件，若在 n 秒内被重复触发，则重新计时
      const debounce = (fn, delay = 500) => {
        let timer
        return function (...args) {
          if (timer) clearTimeout(timer)
          timer = setTimeout(() => {
            fn.apply(this, args)
          }, delay)
        }
      }

      // 节流 ：n 秒内只运行一次，若在 n 秒内重复触发，只有一次生效
      const throttle = (fn, delay = 500) => {
        let timer
        return function (...args) {
          if (timer) return
          timer = setTimeout(() => {
            fn.apply(this, args)
            timer = null // 重置 timer
          }, delay)
        }
      }

      // 使用示例
      const obj = {
        name: '测试对象',
        handleClick: function () {
          console.log(this)
          console.log('点击了:', this.name)
        },
      }

      // 应用防抖
      obj.debouncedClick = debounce(obj.handleClick, 300)
      // 应用节流
      obj.throttledClick = throttle(obj.handleClick, 300)
      btn.addEventListener('click', obj.debouncedClick)
      btn.addEventListener('click', obj.throttledClick)
    </script>
  </body>
</html>
